package com.twu.biblioteca.engine;

import com.twu.biblioteca.command.Command;
import com.twu.biblioteca.command.CommandFactory;
import com.twu.biblioteca.security.SecuritySupport;

import java.util.Scanner;

import static com.twu.biblioteca.util.ConsoleUtil.print;
import static com.twu.biblioteca.util.ConsoleUtil.println;
import static com.twu.biblioteca.util.ConsoleUtil.printError;

public class Engine {

    private static Scanner scanner = new Scanner(System.in);

    public static void start(CommandFactory commandFactory, SecuritySupport securitySupport) {
        String line;
        while (!"Quit".equals((line = scanner.nextLine()))) {
            Command command = commandFactory.getCommand(line);
            if (securitySupport.authenticatedRequired(command.getClass())
                    && !securitySupport.authenticate(askForUserId(), askForPassword())) {
                printError("your password or id is correct");
                continue;
            }
            execute(scanner, command);
        }
    }

    private static String askForPassword() {
        print("please input your password: ");
        return scanner.nextLine();
    }

    private static String askForUserId() {
        print("please input your id: ");
        return scanner.nextLine();
    }

    private static void execute(Scanner scanner, Command command) {
        if (command.hasSubParam()) {
            println(command.subParamTips());
            command.parameter(getSubParameter(scanner.nextLine()));
        }
        String result = command.execute();
        println(result);
    }

    private static String[] getSubParameter(String line) {
        return new String[]{line};
    }
}
